var http = require("http");
var url = require("url");
var pg = require('pg');
http.createServer(function(request, response) {
     var path = url.parse(request.url, true).path;
	 if(7==path.length) {
	    path = path.substr(1);
		pg.connect("postgres://postgres:123456@127.0.0.1/monografia", function(err, client, done) {
			if(!err) {
				client.query('SELECT hash, url, datacriacao FROM url WHERE hash = \'' + path + '\'',function(err,result) {
				    //libera a conexão
					done();
				    if(!err && result.rowCount==1) {
						var sUrl = 'http://'+result.rows[0]['url'];
						response.writeHead (301, {'Location': sUrl});
				    }
				    else {
						response.writeHead(404);
				    }
				    response.end();
				});
			}
			else {
				response.writeHead(404);
				response.end();
			}
		});
	 }
	 else {
		response.writeHead(404);
		response.end();
	 }	
}).listen(80);
console.log("Server Running... 80");
